package appctl

import (
	"blog/conf"
	"blog/service"
	"fmt"
	"github.com/labstack/echo/v4"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"github.com/zxysilent/utils"
	"golang.org/x/net/context"
	"strconv"
	"time"
)

func BaseInfo(ctx echo.Context) error {
	info := service.CommonService.GetBaseInfo()

	return ctx.JSON(utils.Succ("succ", info))
}

//获取七牛云文件上传token
func GetFiletUploadToken(ctx echo.Context) error {
	return ctx.JSON(utils.Succ("succ", get76Token()))
}

// 上传文件到七牛云
func UploadFile276(ctx echo.Context) error {
	upToken := get76Token()

	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuadong
	// 是否使用https域名
	cfg.UseHTTPS = true
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false

	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	file, _ := ctx.FormFile("file")
	src, _ := file.Open()
	defer src.Close()

	fileNam := strconv.Itoa(time.Now().Nanosecond()) + ".png"
	putExtra := storage.PutExtra{
		Params: map[string]string{
			"x:name": fileNam,
		},
	}

	err := formUploader.Put(context.Background(), &ret, upToken, fileNam, src, file.Size, &putExtra)
	if err != nil {
		fmt.Println(err)
		return err
	}
	fmt.Println(ret.Key, ret.Hash)
	return ctx.JSON(utils.Succ("succ", conf.AppConf.Qiniu.Resurl+fileNam))
}

func get76Token() string {
	bucket := conf.AppConf.Qiniu.Bucket
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	mac := qbox.NewMac(conf.AppConf.Qiniu.AccessKey, conf.AppConf.Qiniu.SecretKey)
	upToken := putPolicy.UploadToken(mac)
	return upToken
}
